package org.adream.account.util;

import com.google.common.base.Strings;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

/**
 * 文件操作类
 *
 * @author sl
 */
public class FileUtils {

    private final static Logger logger = LoggerFactory.getLogger(FileUtils.class);


    private FileUtils() {


    }

    private static Boolean enableCos;

    static {
        //加载需要的配置文件
        enableCos = Boolean.valueOf(Utils.readProperty("config/jdbc.properties", "file.cos.enable"));
    }

    /**
     * 文件路径转为byte数组
     *
     * @param file
     * @return
     */
    public static byte[] readFileToByteArray(String file) {
        byte[] data = null;
        try {
            if (!Strings.isNullOrEmpty(file)) {
                data = Files.readAllBytes((new File(file)).toPath());
            }
        } catch (Exception e) {
            if (logger.isInfoEnabled()) {
                logger.info("下载文件出错", e.getMessage());
            }
        }
        return data;
    }

    public static void readFile(String file, HttpServletResponse response) {
        readFile(file, response, 0, 0);
    }


    public static void readFile(String file, HttpServletResponse response, int width, int height) {
        if (enableCos) {
            try {
                CosFileUtil.getSingle().getObject(file, response, width, height);
            } catch (Exception e) {
                logger.info("图片浏览失败:)");
            }
            return;
        }
        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream();
        ) {
            if (width > 0 && height > 0) {
                String ext = file.substring(file.lastIndexOf("."));
                String picName = file.substring(0, file.lastIndexOf("."));
                Thumbnails.of(file).size(width, height).toFile(picName + "_" + height + "x" + width + ext);
                file = picName + "_" + height + "x" + width + ext;
            }

            int count = 0;
            byte[] buffer = new byte[1024 * 8];
            while ((count = fis.read(buffer)) != -1) {
                os.write(buffer, 0, count);
                os.flush();
            }
        } catch (Exception e) {
            logger.info("图片浏览失败:)");
        }
    }


    public static void downFile(String file, HttpServletResponse response) {
        if (enableCos) {
            try {
                CosFileUtil.getSingle().downFile(file,response);
            } catch (IOException e) {
                logger.info("文件下载失败:)");
            }
            return;
        }
        try (InputStream ins = new FileInputStream(file);
             OutputStream os = response.getOutputStream();
        ) {
            /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
            response.setContentType("multipart/form-data");
            /* 设置文件头：最后一个参数是设置下载文件名 */
            response.setHeader("Content-Disposition",
                    "filename=" + new String(new File(file).getName().getBytes("UTF-8"), "ISO8859-1"));
            byte[] b = new byte[1024];
            int len;
            while ((len = ins.read(b)) > 0) {
                os.write(b, 0, len);
            }
            os.flush();
        } catch (IOException ioe) {
            logger.info("文件下载失败:)");
        }
    }

    /**
     * 写文件
     *
     * @param file
     * @param is
     */
    public static void writeToFile(File file, InputStream is) {
        if (is == null || file == null || file.isDirectory()) {
            return;
        }
        if (enableCos) {
            String oriPath = file.getPath();
            try {
                CosFileUtil.getSingle().putObjectFlex(oriPath, is);
            } catch (Exception e) {
                if (logger.isInfoEnabled()) {
                    logger.info("写文件时出错", e);
                }
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return;
        }
        //上传文件到本地服务器
        try (OutputStream os = new FileOutputStream(file)) {
            byte[] bs = new byte[1024 * 1024];
            int len = 0;
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            if (logger.isInfoEnabled()) {
                logger.info("写文件时出错", e);
            }
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    /**
     * 删除文件
     *
     * @param file
     */
    public static void deleteFile(String file) {
        try {
            File fileTemp = new File(file);
            if (fileTemp.isFile() && fileTemp.exists()) {
                fileTemp.delete();
            }
        } catch (Exception e) {
            if (logger.isInfoEnabled()) {
                logger.info("删除文件时出错", e);
            }
        }
    }
}
